O(NP) algorithm